package cv.gzd.robot.socket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author: Jun
 * @Date: 2018/8/21 14:53
 */
public class Handshake extends HttpSessionHandshakeInterceptor {

    //当有新的websocket连接进入时触发
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        System.out.println("beforeHandshake");
        if((((ServletServerHttpRequest) serverHttpRequest).getServletRequest().getSession(false).getAttribute("rid"))!=null){
            System.out.println("Websocket:设备[ID" + (((ServletServerHttpRequest) serverHttpRequest).getServletRequest().getSession(false).getAttribute("rid")) + "]已经建立连接");
        }
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            Integer rid= (Integer) session.getAttribute("rid");
            if (rid!=null) {
                map.put("rid",rid);
            } else {
                return false;
            }
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("afterHandshake");
    }
}